﻿using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;

namespace MetadataDesignerLibrary
{
    public class MethodSpecificationRule : ILRule<MethodSpecificationHandle>
    {
        [ILInfo(true)]
        public EntityHandle Method { get; }

        public byte[] Signature { get; }

        [ILInfo(ILInfoParseMethod.AsEntityHandleCollection)]
        public CustomAttributeHandleCollection CustomAttributes { get; }

        public MethodSpecificationRule(
            EntityHandle method,
            byte[] signature)
            : base()
        {
            Method = method;
            Signature = signature;
        }

        public MethodSpecificationRule(MetadataReader reader, MethodSpecificationHandle methodSpecificationHandle)
            : base(reader)
        {
            MethodSpecification methodSpecification = reader.GetMethodSpecification(methodSpecificationHandle);
            Method = methodSpecification.Method;
            Signature = reader.GetBlobBytes(methodSpecification.Signature);
            CustomAttributes = methodSpecification.GetCustomAttributes();
        }

        public override MethodSpecificationHandle Write(MetadataDesigner designer)
        {
            MetadataBuilder builder = designer.Builder;
            return builder.AddMethodSpecification(
                method: Method,
                instantiation: Signature == null ? default : builder.GetOrAddBlob(Signature));
        }
    }
}